/**
 * @description 数据读取器
*/

const fs = require('fs')
const path = require('path')

class DatarFile {
  /**
   * @function 根据文件地址获取数据
   * @param {String} fPath
   * @return {Object}
  */
  read (fPath) {
    let data = ''
    let text = ''
    if(fs.existsSync(fPath)) {
      data = fs.readFileSync(fPath, 'utf8')
      text = data.toString()
    }
    return {
      data: text,
      text: text
    }
  }

  /**
   * @function 根据文件地址写数据
   * @param {String} fPath
   * @return {Object}
  */
  write (fPath, text) {
    let dir = path.parse(fPath).dir
    if(!fs.existsSync(dir)) {
      this.buildPath(dir)
    }
    try {
      fs.writeFileSync(fPath, text, { 
        encoding: 'utf8'
      })
      return true
    } catch (e) {
      return e
    }
  }

  /**
   * @function 根据文件地址清除数据
   * @param {String} fPath
   * @return {Object}
  */
  clear (fPath) {
    if(!fs.existsSync(fPath)) {
      return false
    }
    try {
      fs.rmSync(fPath)
      return true
    } catch (e) {
      return e
    }
  }

  /**
   * @function 根据文件地址获取数据
   * @param {String} fPath
   * @return {Object}
  */
  readJSON (fPath) {
    let data = ''
    let text = ''
    if(fs.existsSync(fPath)) {
      data = fs.readFileSync(fPath, 'utf8')
      text = data.toString()
    }
    try {
      data = JSON.parse(text)
    } catch (e) {
      data = text
    }

    return {
      data: data,
      text: text
    }
  }

  /**
   * @function 根据文件地址写数据
   * @param {String} fPath
   * @return {Object}
  */
  writeJSON (fPath, text) {
    let dir = path.parse(fPath).dir
    if(!fs.existsSync(dir)) {
      this.buildPath(dir)
    }
    let data = text
    try {
      if (typeof data === 'object') {
        data = JSON.stringify(text, null, '  ')
      }
    } catch (e) {
      data = text
    }
    try {
      fs.writeFileSync(fPath, data, { 
        encoding: 'utf8'
      })
      return true
    } catch (e) {
      return e
    }
  }

  /**
   * @function 创建路径
   * @param {String} folderpath
  */
  buildPath (folderpath) {
    if (typeof folderpath !== 'string') {
      return false
    }
    folderpath = resolve(folderpath).replace(/\\/g, '/')
    const pathArr = folderpath.split('/')
    let _path = ''
    for (let i = 0; i < pathArr.length; i++) {
      // 盘符
      if (!i && /\w+:/.test(pathArr[i])) {
        _path += pathArr[i]
      }
      else if (pathArr[i]) {
        _path += `/${pathArr[i]}`
        if (!fs.existsSync(_path)) {
          fs.mkdirSync(_path)
        }
      }
    }
  }
}

module.exports = DatarFile